package com.apache.bid.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.apache.api.vo.ParamsVo;
import com.apache.bid.common.Constant;
import com.apache.bid.common.cache.BidCacheFactory;
import com.apache.bid.common.cache.BidCacheManager;
import com.apache.bid.entity.BidApply;
import com.apache.bid.manager.BidApplyManager;
import com.apache.cache.util.Validator;
import com.apache.database.db.IDao;
import com.apache.database.model.MethodParam;
import com.apache.database.model.Page;
import com.apache.exception.BusinessException;
import com.apache.rpc.util.LoadRpcService;
import com.apache.tools.DateUtils;

public class BidApplyManagerImpl implements BidApplyManager {

	protected IDao bidApplyDao;
	protected final String entityName = "com.apache.bid.entity.BidApply";

	public void setBidApplyDao(IDao bidApplyDao) {
		this.bidApplyDao = bidApplyDao;
	}

	public String saveInfo(ParamsVo<BidApply> vo) throws BusinessException {
		BidApply bidApply = initBidApply(vo.getObj());
		//定义对象缓存KEY,如果不需要缓存对象请不要对变量赋值，如果要缓存对象建议使用infoId
		String cacheKey = "";
		//String cacheKey="bidApply_"+infoId;
		if (Validator.isNull(bidApply.getApplyId())) {
			String infoId = Validator.generate();
			bidApply.setApplyId(infoId);
		}
		if (Constant.getInstance().ifWriteDatabase()) {
			bidApply.setCreateTime(DateUtils.Now.fmt_yyyyMMdd_HHmmss());
			MethodParam param = new MethodParam("BidApply", cacheKey, "", entityName);
			param.setVaule(bidApply);
			if (bidApplyDao.insert(param)) {
				return bidApply.getApplyId();
			}
		} else {
			///////////////需要处理缓存结果//////////////////
			vo.setParams("methodCode", "saveApply");
			return bidApply.getApplyId();
		}
		return "";
	}

	/**
	 * description:  添加信息默认值
	 */
	private BidApply initBidApply(BidApply apply) {
		if (Validator.isNull(apply.getSessionId())) {
			apply.setSessionId("0");
		}
		if (Validator.isNull(apply.getItemId())) {
			apply.setItemId("0");
		}
		if (Validator.isNull(apply.getIfRight())) {//是否申请使用允许行权（T/F）
			apply.setIfRight("F");
		}
		if (Validator.isNull(apply.getApplyWay())) {//报名方式 "0":现场报名  "1":网上报名
			apply.setApplyWay("1");
		}
		if (Validator.isNull(apply.getStatus())) {//状态（0=未激活，1=已激活）
			apply.setStatus("0");
		}
		if (Validator.isNull(apply.getBailFinshFlag())) {//保证金状态(0=待交，1=部分交，2=全交，3=已退保）
			apply.setBailFinshFlag("0");
		}
		if (Validator.isNull(apply.getBailPayMode())) {//保证金支付方式（0在线支付、1支票、2银行转账、3现金、4其他）
			apply.setBailPayMode("0");
		}
		return apply;
	}

	@SuppressWarnings("rawtypes")
	public boolean editInfo(ParamsVo<BidApply> vo) throws BusinessException {
		String key = vo.getMethodKey();
		if (Constant.getInstance().ifWriteDatabase()) {
			if (Validator.isNull(key)) {
				BidApply bidApply = vo.getObj();
				String applyId = bidApply.getApplyId();
				if (Validator.isNotNull(applyId)) {
					String cacheKey = "";
					//String cacheKey="bidItem_"+bidItem.getItemid();
					bidApply.setModifyTime(DateUtils.Now.fmt_yyyyMMdd_HHmmss());
					MethodParam param = new MethodParam("BidApply", cacheKey, "", entityName);
					param.setVaule(bidApply);
					boolean mark = bidApplyDao.edit(param);
					if (mark) {
						//更新缓存
						param.setKey("ById");
						param.setInfoId(applyId);
						bidApply = (BidApply) bidApplyDao.selectById(param);
						BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("apply");
						cache.createCacheObject(bidApply);
					}
					return mark;
				}
			} else if ("BidApplyForStatus".equals(key)) {//用户激活
				String applyId = vo.getInfoId();
				String status = String.valueOf(vo.getParams("status"));
				MethodParam param = new MethodParam("BidApplyForStatus", "", "", entityName);
				param.setParams("applyId", applyId);
				param.setParams("status", status);
				boolean mark = bidApplyDao.edit(param);
				if (mark) {
					BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("apply");
					BidApply bidApply = (BidApply) cache.getCacheCloneByKey(BidCacheManager.apply_prefix + applyId);
					if (!Validator.isEmpty(bidApply)) {
						bidApply.setStatus(status);
						cache.updateCacheObject(bidApply);
						sendActivationApplyMsg(bidApply);
					}
				}
				return mark;
			}
		} else {
			if ("BidApplyForStatus".equals(key)) {
				vo.setParams("infoId", vo.getInfoId());
				vo.setParams("MethodKey", key);
			}
			///////////////需要处理缓存结果//////////////////
			vo.setParams("methodCode", "editApply");
			return true;
		}
		return false;
	}

	@SuppressWarnings("rawtypes")
	public boolean deleteInfo(ParamsVo<BidApply> vo) throws BusinessException {
		String infoId = vo.getInfoId();
		if (Validator.isNull(infoId)) {
			BidApply apply = vo.getObj();
			if (Validator.isEmpty(apply)
					|| (Validator.isNull(apply.getItemId()) && Validator.isNull(apply.getSessionId())))
				return false;
			MethodParam param = new MethodParam("ByObjeId", "", "", entityName);
			if (Validator.isNotNull(apply.getItemId()))
				param.setParams("itemId", apply.getItemId());
			if (Validator.isNotNull(apply.getSessionId()))
				param.setParams("sessionId", apply.getSessionId());
			param.setDelete(true);
			return bidApplyDao.delete(param);
		}
		String cacheKey = "";
		//String cacheKey="bidApply_"+infoId;
		String mark = Validator.getDefaultStr(String.valueOf(vo.getParams("isDelete")), "true");
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		if (Constant.getInstance().ifWriteDatabase()) {
			boolean markC = false;
			param.setInfoId(infoId);
			BidApply info = (BidApply) bidApplyDao.selectById(param);
			if (Validator.isEmpty(info)) {
				return false;
			}
			if ("false".equals(mark)) {//逻辑删除
				param.setVaule(info);//此处需要先将状态值赋值为删除状态
				param.setKey("BidApply");
				markC = bidApplyDao.edit(param);
			} else {
				param.setParams("applyId", infoId);
				param.setDelete(true);
				markC = bidApplyDao.delete(param);
			}
			if (markC) {
				BidCacheManager cache = BidCacheFactory.getInstance().getCacheManager("apply");
				String key = BidCacheManager.apply_prefix + info.getUserName() + "_";
				if ("0".equals(info.getSessionId())) {
					key += info.getItemId();
				} else {
					key += info.getSessionId();
				}
				cache.removeCacheObject(key);
			}
			return markC;
		} else {
			///////////////需要处理缓存结果//////////////////
			if ("false".equals(mark)) {

			} else {

			}
			vo.setParams("methodCode", "deleteApply");
			return true;
		}
	}

	public Object getInfoById(ParamsVo<BidApply> vo) {
		String infoId = vo.getInfoId();
		String cacheKey = "";
		//String cacheKey="bidApply_"+infoId;
		if (Validator.isNull(infoId)) {
			return null;
		}
		MethodParam param = new MethodParam("ById", cacheKey, "", entityName);
		param.setInfoId(infoId);
		return bidApplyDao.selectById(param);
	}

	public Object execute(ParamsVo<BidApply> vo) {
		String key = vo.getMethodKey();

		if ("singleApplyByAttr".equalsIgnoreCase(key)) {
			return this.getBidApplyByAttr(vo.getObj());
		}
		return null;
	}

	//报名的时候存在itemId=0,通过sessionId和userName查出单条数据
	private BidApply getBidApplyByAttr(BidApply bidApply) {

		MethodParam param = new MethodParam("ByBidApplyAttr", "", "", entityName);
		StringBuffer sb = new StringBuffer();
		if (Validator.isNotNull(bidApply.getItemId())) {
			sb.append(" and itemId =:itemId");
			param.setParams("itemId", bidApply.getItemId());
		}
		if (Validator.isNotNull(bidApply.getSessionId())) {
			sb.append(" and sessionId =:sessionId");
			param.setParams("sessionId", bidApply.getSessionId());
		}
		if (Validator.isNotNull(bidApply.getUserName())) {
			sb.append(" and userName =:userName");
			param.setParams("userName", " = '" + bidApply.getUserName() + "' ");
		}
		if (!Validator.isNull(sb.toString())) {
			param.setSqlStr(bidApplyDao.getSql(2) + sb.toString());
			BidApply apply = (BidApply) bidApplyDao.selectSingle(param);
			return apply;
		} else {
			return null;
		}
	}

	public Page getPageInfo(ParamsVo<BidApply> vo) {
		MethodParam param = setMethodParams(vo, 2);
		int pageSize = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageSize")), "10"));
		int pageIndex = Integer.valueOf(Validator.getDefaultStr(String.valueOf(vo.getParams("pageIndex")), "1"));
		param.setPageIndex(pageIndex);
		param.setPageSize(pageSize);
		//param.setOrderby(" create_time desc");
		String orderBy = Validator
				.getDefaultStr(String.valueOf(vo.getParams("orderBy")), " order by create_time desc ");
		param.setParams("orderBy", orderBy);
		Page page = bidApplyDao.pageSelect(param);
		return page;
	}

	public List<BidApply> getList(ParamsVo<BidApply> vo) {
		MethodParam param = setMethodParams(vo, 2);
		//param.setOrderby(" create_time desc");
		String orderBy = Validator
				.getDefaultStr(String.valueOf(vo.getParams("orderBy")), " order by create_time desc ");
		param.setParams("orderBy", orderBy);
		return bidApplyDao.select(param);
	}

	public long countInfo(ParamsVo<BidApply> vo) {
		MethodParam param = setMethodParams(vo, 1);
		return bidApplyDao.count(param);
	}

	private MethodParam setMethodParams(ParamsVo<BidApply> vo, int type) {
		String methodKey = Validator.getDefaultStr(vo.getMethodKey(), "ByProperty");
		StringBuffer sb = new StringBuffer(bidApplyDao.getSql(type));
		MethodParam param = new MethodParam(methodKey, "", "", entityName);
		param.setResultCache(false);
		BidApply bidApply = vo.getObj();
		if (Validator.isEmpty(bidApply))
			return param;
		if (Validator.isNotNull(bidApply.getApplyId())) {
			sb.append(" and applyId = :applyId");
			param.setParams("applyId", bidApply.getApplyId());
		}
		if (Validator.isNotNull(bidApply.getSessionId())) {
			sb.append(" and sessionId = :sessionId");
			param.setParams("sessionId", bidApply.getSessionId());
		}
		if (Validator.isNotNull(bidApply.getUserType())) {
			sb.append(" and userType = :userType");
			param.setParams("userType", bidApply.getUserType());
		}
		if (Validator.isNotNull(bidApply.getUserId())) {
			sb.append(" and userId = :userId");
			param.setParams("userId", bidApply.getUserId());
		}
		if (Validator.isNotNull(bidApply.getItemId())) {
			sb.append(" and itemId = :itemId");
			param.setParams("itemId", bidApply.getItemId());
		}
		if (Validator.isNotNull(bidApply.getRole())) {
			sb.append(" and role = :role");
			param.setParams("role", bidApply.getRole());
		}
		if (Validator.isNotNull(bidApply.getBidUserNo())) {
			sb.append(" and bidUserNo = :bidUserNo");
			param.setParams("bidUserNo", bidApply.getBidUserNo());
		}
		if (Validator.isNotNull(bidApply.getCreateTime())) {
			sb.append(" and createTime = :createTime");
			param.setParams("createTime", bidApply.getCreateTime());
		}
		if (Validator.isNotNull(bidApply.getModifyTime())) {
			sb.append(" and modifyTime = :modifyTime");
			param.setParams("modifyTime", bidApply.getModifyTime());
		}
		if (Validator.isNotNull(bidApply.getIfRight())) {
			sb.append(" and ifRight = :ifRight");
			param.setParams("ifRight", bidApply.getIfRight());
		}
		if (Validator.isNotNull(bidApply.getUserName())) {
			sb.append(" and userName like '%" + bidApply.getUserName() + "%' ");
			param.setParams("userName", " like '%" + bidApply.getUserName() + "%' ");
		}
		if (Validator.isNotNull(bidApply.getRealName())) {
			sb.append(" and realName = :realName");
			param.setParams("realName", bidApply.getRealName());
		}
		if (Validator.isNotNull(bidApply.getAllowBuyNum())) {
			sb.append(" and allowBuyNum = :allowBuyNum");
			param.setParams("allowBuyNum", bidApply.getAllowBuyNum());
		}
		if (Validator.isNotNull(bidApply.getSczlTime())) {
			sb.append(" and sczlTime = :sczlTime");
			param.setParams("sczlTime", bidApply.getSczlTime());
		}
		if (Validator.isNotNull(bidApply.getApplyWay())) {
			sb.append(" and applyWay = :applyWay");
			param.setParams("applyWay", bidApply.getApplyWay());
		}
		if (Validator.isNotNull(bidApply.getReadRule())) {
			sb.append(" and readRule = :readRule");
			param.setParams("readRule", bidApply.getReadRule());
		}
		if (Validator.isNotNull(bidApply.getCustomerNo())) {
			sb.append(" and customerNo = :customerNo");
			param.setParams("customerNo", bidApply.getCustomerNo());
		}
		if (Validator.isNotNull(bidApply.getCustomerName())) {
			sb.append(" and customerName = :customerName");
			param.setParams("customerName", bidApply.getCustomerName());
		}
		if (Validator.isNotNull(bidApply.getCustomerStatus())) {
			sb.append(" and customerStatus = :customerStatus");
			param.setParams("customerStatus", bidApply.getCustomerStatus());
		}
		if (Validator.isNotNull(bidApply.getProvince())) {
			sb.append(" and province = :province");
			param.setParams("province", bidApply.getProvince());
		}
		if (Validator.isNotNull(bidApply.getCity())) {
			sb.append(" and city = :city");
			param.setParams("city", bidApply.getCity());
		}
		if (Validator.isNotNull(bidApply.getDist())) {
			sb.append(" and dist = :dist");
			param.setParams("dist", bidApply.getDist());
		}
		if (Validator.isNotNull(bidApply.getPhone())) {
			sb.append(" and phone = :phone");
			param.setParams("phone", bidApply.getPhone());
		}
		if (Validator.isNotNull(bidApply.getMobile())) {
			sb.append(" and mobile = :mobile");
			param.setParams("mobile", bidApply.getMobile());
		}
		if (Validator.isNotNull(bidApply.getCertType())) {
			sb.append(" and certType = :certType");
			param.setParams("certType", bidApply.getCertType());
		}
		if (Validator.isNotNull(bidApply.getCertNo())) {
			sb.append(" and certNo = :certNo");
			param.setParams("certNo", bidApply.getCertNo());
		}
		if (Validator.isNotNull(bidApply.getEmail())) {
			sb.append(" and email = :email");
			param.setParams("email", bidApply.getEmail());
		}
		if (Validator.isNotNull(bidApply.getFax())) {
			sb.append(" and fax = :fax");
			param.setParams("fax", bidApply.getFax());
		}
		if (Validator.isNotNull(bidApply.getCompany())) {
			sb.append(" and company = :company");
			param.setParams("company", bidApply.getCompany());
		}
		if (Validator.isNotNull(bidApply.getBailPayMode())) {
			sb.append(" and bailPayMode = :bailPayMode");
			param.setParams("bailPayMode", bidApply.getBailPayMode());
		}
		if (Validator.isNotNull(bidApply.getBank())) {
			sb.append(" and bank = :bank");
			param.setParams("bank", bidApply.getBank());
		}
		if (Validator.isNotNull(bidApply.getBankAccount())) {
			sb.append(" and bankAccount = :bankAccount");
			param.setParams("bankAccount", bidApply.getBankAccount());
		}
		if (Validator.isNotNull(bidApply.getShouldBail())) {
			sb.append(" and shouldBail = :shouldBail");
			param.setParams("shouldBail", bidApply.getShouldBail());
		}
		if (Validator.isNotNull(bidApply.getFactBail())) {
			sb.append(" and factBail = :factBail");
			param.setParams("factBail", bidApply.getFactBail());
		}
		if (Validator.isNotNull(bidApply.getFactBailTime())) {
			sb.append(" and factBailTime = :factBailTime");
			param.setParams("factBailTime", bidApply.getFactBailTime());
		}
		if (Validator.isNotNull(bidApply.getFactBailAccount())) {
			sb.append(" and factBailAccount = :factBailAccount");
			param.setParams("factBailAccount", bidApply.getFactBailAccount());
		}
		if (Validator.isNotNull(bidApply.getBailFinshFlag())) {
			sb.append(" and bailFinshFlag = :bailFinshFlag");
			param.setParams("bailFinshFlag", bidApply.getBailFinshFlag());
		}
		if (Validator.isNotNull(bidApply.getStatus())) {
			sb.append(" and status = :status");
			param.setParams("status", bidApply.getStatus());
		}
		if (Validator.isNotNull(bidApply.getOrgEname())) {
			sb.append(" and orgEname = :orgEname");
			param.setParams("orgEname", bidApply.getOrgEname());
		}
		if (Validator.isNotNull(bidApply.getPayFlowNo())) {
			sb.append(" and payFlowNo = :payFlowNo");
			param.setParams("payFlowNo", bidApply.getPayFlowNo());
		}
		if (Validator.isNotNull(bidApply.getSpare1())) {
			sb.append(" and spare1 = :spare1");
			param.setParams("spare1", bidApply.getSpare1());
		}
		if (Validator.isNotNull(bidApply.getSpare2())) {
			sb.append(" and spare2 = :spare2");
			param.setParams("spare2", bidApply.getSpare2());
		}
		if (Validator.isNotNull(bidApply.getSpare3())) {
			sb.append(" and spare3 = :spare3");
			param.setParams("spare3", bidApply.getSpare3());
		}
		if (Validator.isNotNull(bidApply.getSpare4())) {
			sb.append(" and spare4 = :spare4");
			param.setParams("spare4", bidApply.getSpare4());
		}
		if (Validator.isNotNull(bidApply.getSpare5())) {
			sb.append(" and spare5 = :spare5");
			param.setParams("spare5", bidApply.getSpare5());
		}
		if (Validator.isNotNull(bidApply.getObjName())) {
			sb.append(" and objName  like '%" + bidApply.getObjName() + "%' ");
			param.setParams("objName", " like '%" + bidApply.getObjName() + "%' ");
		}
		if (Validator.isNotNull(bidApply.getApplyName())) {
			sb.append(" and applyName = :applyName");
			param.setParams("applyName", bidApply.getApplyName());
		}

		param.setSqlStr(sb.toString());
		return param;
	}

	/**
	 * description:  发送竞买人激活通知
	 */
	private void sendActivationApplyMsg(BidApply apply) {
		Map<String, Object> params = new HashMap<String, Object>();
		String content = "";
		String title = "";
		if ("1".equals(apply.getStatus())) {
			content = "恭喜您,您申请竞买" + apply.getObjName() + "的资格已被确认并激活，请您及时参数竞标活动。";
			title = "【" + apply.getObjName() + "】竞买资格确认通知";
		} else {
			content = "很遗憾,您申请竞买" + apply.getObjName() + "的资格未通过审核，谢谢您的参与。";
			title = "【" + apply.getObjName() + "】竞买资格未通过通知";
		}
		params.put("msgContent", content);
		params.put("msgTitle", title);
		if (Validator.isNotNull(apply.getMobile())) {
			params.put("toUserMobile", apply.getMobile());
			params.put("msgType", "mobile");
		}
		if (Validator.isNotNull(apply.getEmail())) {
			params.put("toUserEmail", apply.getEmail());
			params.put("msgType", "email");
		}
		if (Validator.isNotNull(apply.getEmail()) && Validator.isNotNull(apply.getEmail())) {
			params.put("msgType", "all");
		}
		params.put("toUserName", apply.getUserName());
		params.put("sysEname", "wbd");
		params.put("fromUserName", "平台");
		LoadRpcService.service().doService("sendmsgService", "saveMsg", "XML", params, null);
	}
}
